#include "char-input-stream.h"

#include <assert.h>


bool UnescapeCharInputStream::hasNext() {
    if (st_ == State::NoNextChar) {
        return false;
    }
    tryLoadNextChar();
    return st_ != State::NoNextChar;
}

char UnescapeCharInputStream::next() {
    if (st_ == State::NoNextChar) {
        return 0;
    }
    tryLoadNextChar();
    char c = nextChar_;
    nextChar_ = 0;
    st_ = State::NextCharNotLoaded;
    return c;
}

void UnescapeCharInputStream::tryLoadNextChar() {
    assert(st_ != State::NoNextChar && "this should be checked by outer logic");
    if (st_ == State::NextCharLoaded) {
        return;
    }
    assert(st_ == State::NextCharNotLoaded);
    if (!in_.hasNext()) {
        st_ = State::NoNextChar;
        return;
    }
    const char c = in_.next();
    if (c != '\\') {
        nextChar_ = c;
        st_ = State::NextCharLoaded;
        return;
    }
    if (!in_.hasNext()) {
        st_ = State::NoNextChar;
        return;
    }
    nextChar_ = in_.next();
    st_ = State::NextCharLoaded;
    return;
}

